<template lang="html">
  <div class="content-container bookMgr-source-container">

    <div class="content-condition filter searchBox" id="filterId">
      <div class="filterBtn">
        <el-button type='primary' @click="searchFun" :icon="Search">搜索</el-button>
        <el-button type="danger" @click="resetSearchData" :icon="RefreshRight">重置</el-button>
      </div>

      <el-input v-model="searchData.name" :clearable="true" placeholder="书源名称" style="width: 180px"> </el-input>
      <el-input v-model="searchData.sourceKey" :clearable="true" placeholder="书源Key" style="width: 180px"> </el-input>

    </div>

    <el-row class="special content-condition buttonBox" id="buttonId">
      <el-col :span="24" ref="limitBtnWidth">
        <el-space :size="10" id="actualBtnWidth" class="actualBtnWidth">
          <el-button type="primary" @click="addFun" :icon="Plus">新增</el-button>
          <el-button type="success" @click="editFun" :icon="Edit">编辑</el-button>
          <el-button type="danger" @click="deleteFun" :icon="Delete">删除</el-button>
        </el-space>
      </el-col>
    </el-row>


    <!--表格-->
    <div class="table content-condition">
      <common-table :isShowLoading="tableData.poolIsShowLoading" :tableId="tableData.tableId"
        :columns="tableData.columns" emptyText="没有找到数据" :data="tableData.datas" :tableType="tableData.tableType"
        :pager="tableData.pager" @handleCurrentChange="handleCurrentChange" @handleSizeChange="handleSizeChange"
        @handleSelectionChange="handleSelectionChange" @handleExpandChange="handleExpandChange" :rowkey="'id'"
        :expandRowKeys="tableData.expandRowKeys" ref="table">
        <template v-slot:table_checkbox>
          <el-table-column type="selection" align="center" width="55" fixed="left"></el-table-column>
        </template>

        <template #enableSlot="slotData">
          <el-switch v-model="slotData.scope.row.enabled" @change="switchEnableFun(slotData.scope.row)"
            :active-value="true" :inactive-value="false" active-text="启用" inactive-text="禁用" />
        </template>
      </common-table>
    </div>
  </div>
  <Detail ref="settingDetailDialog"></Detail>
</template>
<script setup lang="js">
import { onMounted, ref, inject, provide } from 'vue';
import { Edit, Delete, Plus, Search, RefreshRight } from '@element-plus/icons-vue';
import _ from 'lodash';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getSettingPageList, switchEnable, deleteSetting } from '@/api/bookSourceSetting';
import Detail from './components/Detail.vue';

const initSearchData = () => {
  return {
    name: '',
    sourceKey: '',
    pageIndex: 0,
    pageSize: 20,
  };
};
const settingDetailDialog = ref(null); // 书源设置详情弹窗
const searchData = ref(initSearchData());

const tableData = ref({
  tableId: 'bookSourceTable',
  tableType: ["table"], //table-表格 dualCard-双卡片 其它-单卡片
  columns: [
    {
      prop: "name",
      label: "书源名称",
      width: "60",
      align: "left",
      sortable: false,
      show: true
    },
    {
      prop: "sourceKey",
      label: "书源Key",
      width: "60",
      align: "left",
      sortable: false,
      show: true
    },
    {
      slotName: "enableSlot",
      label: "启用状态",
      width: "60",
      align: "left",
      sortable: false,
      show: true
    },
    {
      prop: "header",
      label: "请求头",
      width: "120",
      align: "left",
      sortable: false,
      show: true
    },
    {
      prop: "url",
      label: "URL",
      width: "120",
      align: "left",
      sortable: false,
      show: true
    },
    {
      prop: "searchUrl",
      label: "搜索URL",
      width: "120",
      align: "left",
      sortable: false,
      show: true
    },
    {
      prop: "spiderRule",
      label: "爬虫规则",
      width: "120",
      align: "left",
      sortable: false,
      show: true
    },
    {
      prop: "createUserName",
      label: "创建人",
      width: "30",
      align: "left",
      sortable: false,
      show: false
    },
    {
      prop: "createDateTime",
      label: "创建时间",
      width: "60",
      align: "left",
      sortable: false,
      show: false
    },
    {
      prop: "updateUserName",
      label: "更新人",
      width: "30",
      align: "left",
      sortable: false,
      show: false
    },
    {
      prop: "updateDateTime",
      label: "更新时间",
      width: "60",
      align: "left",
      sortable: false,
      show: false
    },
  ],
  datas: [],
  pager: {
    //分页栏信息
    pageNo: 1, //第几页
    limit: 20, //每页记录数
    sizes: [10, 20, 50, 200, 500, 1000],
    total: 0, //总记录数
    isShow: true //是否显示
  },
  expandRowKeys: [],
  selectedRows: [],
  poolIsShowLoading: false,
});

// Methods
function searchFun() {
  // 这里可以添加搜索逻辑
  console.log('搜索条件:', searchData.value);
  tableData.value.poolIsShowLoading = true;
  getDataFun();
}

/**
 * 重置
 */
function resetSearchData() {
  Object.assign(searchData.value, initSearchData());
}

/**
 * 获取数据
 */
const getDataFun = _.debounce(() => {
  let params = Object.assign({}, searchData.value);
  getSettingPageList(params).then((res) => {
    tableData.value.datas = res.data.data;
    tableData.value.pager = {
      total: res.data.records,
      limit: res.data.pageSize,
      pageNo: res.data.pageIndex + 1
    };
  }).finally(() => {
    tableData.value.poolIsShowLoading = false;
  });
}, 300);

/**
 * 改变页码
 * @param pageNo 当前页码
 */
function handleCurrentChange(pageNo) {
  searchData.value.pageIndex = pageNo;
  searchFun();
}

/**
 * 改变每页记录数
 * @param pageSize 每页记录数
 */
function handleSizeChange(pageSize) {
  searchData.value.pageSize = pageSize;
  searchFun();
}

/**
 * 处理选中行变化
 * @param selection 选中行数据
 */
function handleSelectionChange(selection) {
  tableData.value.selectedRows = selection;
}

/**
 * 添加
 */
function addFun() {
  settingDetailDialog.value.openDialog();
}

/**
 * 修改
 */
function editFun() {
  if (tableData.value.selectedRows.length !== 1) {
    ElMessage.warning("请选择一条记录进行编辑");
    return;
  }
  settingDetailDialog.value.openDialog(tableData.value.selectedRows[0]);
}
/**
 * 删除
 */
function deleteFun() {
  if (tableData.value.selectedRows.length === 0) {
    ElMessage.warning("请选择任意一条记录进行删除");
    return;
  }

  const ids = tableData.value.selectedRows.map(item => item.id);
  ElMessageBox.confirm('此操作将永久删除选中的书源配置, 是否继续?',
    '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    tableData.value.poolIsShowLoading = true;
    deleteSetting(ids.join(',')).then((res) => {
      if (res == null || !res.isSuccess) {
        ElMessage.error(res.message || "操作失败");
        return;
      }
      ElMessage.success("删除成功");
      searchFun();
    }).finally(() => {
      tableData.value.poolIsShowLoading = false;
    });
  }).catch(() => {
    ElMessage.info("已取消删除操作");
  });
}

/**
 * 切换启用状态
 * @param setting 当前设置项
 */
const switchEnableFun = _.debounce((setting) => {
  switchEnable(setting.id).then((res) => {
    if (res == null || !res.isSuccess) {
      ElMessage.error(res.message || "操作失败");
      return;
    }
    ElMessage.success("操作成功");
    searchFun();
  }).catch(() => {
    ElMessage.error("操作失败，请稍后重试");
  });
}, 300);

provide('bookSourceSettingProvide', {
  onSuccess: searchFun,
})
</script>
<style lang="less"></style>
